package com.tubang.component.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tubang.common.constant.Constants;
import com.tubang.common.util.StringUtils;
import com.tubang.component.entity.CompanyEntity;
import com.tubang.component.entity.UserEntity;
import com.tubang.component.mapper.UserMapper;
import com.tubang.component.service.ICompanyService;
import com.tubang.component.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author wsl
 * @since 2017-11-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {

    @Resource
    private ICompanyService companyService;

    @Override
    public List<UserEntity> selectPageByCompanyId(Page<UserEntity> userEntityPage, List<String> companyIds, String comId, String realName) {
        EntityWrapper<UserEntity> userEntityWrapper = new EntityWrapper<UserEntity>();
        if (StringUtils.isNotEmpty(comId)) {
            userEntityWrapper.eq("company_id", comId);
        } else {
            userEntityWrapper.in("company_id", companyIds);
        }

        userEntityWrapper.eq("enable", Constants.DEFAULT_VAULE_ONE);
        if (StringUtils.isNoneEmpty(realName)) {
            userEntityWrapper.like("real_name", realName);
        }
        Page<UserEntity> userEntitys = selectPage(userEntityPage, userEntityWrapper);
        return userEntitys.getRecords();
    }

    @Override
    public UserEntity selectCompanyUserAdminByCompanyId(String comapnyId, String type) {
        EntityWrapper<UserEntity> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("company_id", comapnyId);
        entityWrapper.eq("user_type", type);
        UserEntity userEntity = selectOne(entityWrapper);
        return userEntity;
    }

    @Override
    public UserEntity selectCompanyUserByUserId(String userId) {
        UserEntity userEntity = selectById(userId);
        if (userEntity != null) {
            String companyId = userEntity.getCompanyId();
            CompanyEntity companyEntity = companyService.selectById(companyId);
            if (companyEntity != null) {
                UserEntity userAdmin = selectCompanyUserAdminByCompanyId(companyId, companyEntity.getType());
                return userAdmin;
            }
        }
        return null;
    }
}

